package com.carease.view.buyer;

import com.carease.util.SqlUtil;
import org.apache.xml.security.Init;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CarsPanel extends JPanel {
	private JTextField jt_text;
	private JTable table;

	/**
	 * Create the panel.
	 */
	public CarsPanel(int buyer_id) {
		setLayout(null);

		JButton jb_search = new JButton("\u67E5\u8BE2");

		jb_search.setBounds(207, 10, 93, 23);
		add(jb_search);

		jt_text = new JTextField();
		jt_text.setBounds(125, 11, 66, 21);
		add(jt_text);
		jt_text.setColumns(10);

		JButton jb_add = new JButton("\u4E0B\u5355");
		jb_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow == -1) {
					JOptionPane.showMessageDialog(null, "请选择一个产品");
				} else {
//					下单
					String sql = "insert tb_transaction values(0,?,?,?,?)";
                    try {
                        SqlUtil.Update(sql, new Object[]{
                                buyer_id,
                                (int)table.getValueAt(selectedRow, 7),
                                (int)table.getValueAt(selectedRow, 1),
                                "进行中"
                        });
						JOptionPane.showMessageDialog(null, "下单成功！");

                    } catch (SQLException ex) {
						JOptionPane.showMessageDialog(null, "下单失败！");
                        throw new RuntimeException(ex);
                    }
                }
			}
		});
		jb_add.setBounds(620, 10, 93, 23);
		add(jb_add);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 43, 731, 399);
		add(scrollPane);

		table = new JTable();
		scrollPane.setViewportView(table);
		
		JLabel lblNewLabel = new JLabel("\u7C7B\u578B");
		lblNewLabel.setBounds(85, 14, 54, 15);
		add(lblNewLabel);
		jb_search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				initTable(jt_text.getText());
			}
		});
		initTable("");
		

	}
	void initTable(String text){
		String headers[] = {"序号","ID", "类型", "年限", "产商", "里程数", "价格", "发布人ID"};
		if (text.isEmpty()) {
			String sql = "select * from tb_car";
            try {
				ResultSet set = SqlUtil.query(sql, new Object[]{});
				table.setModel(new DefaultTableModel(SqlUtil.getSetArrays(set),headers));
			} catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {
			String sql = "select * from tb_car where type=?";
			try {
				ResultSet set = SqlUtil.query(sql, new Object[]{});
				table.setModel(new DefaultTableModel(SqlUtil.getSetArrays(set),headers));
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}


	}


}
